﻿using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using System.Collections.Concurrent;
using System.Threading.Tasks;
using System.Web;

[HubName("codecast")]
public class CodeCastHub : Hub 
{
    public void Send(string code)
    {        
        Clients.All.refresh(HttpUtility.HtmlEncode(code));
    }
    
    private static readonly ConcurrentDictionary<string, bool>
        _connections = new ConcurrentDictionary<string, bool>();

    public override Task OnConnected()
    {
        _connections.TryAdd(Context.ConnectionId, true);

        return Clients.All.notify(_connections.Count);
    }

    public override Task OnDisconnected()
    {
        bool value;

        _connections.TryRemove(Context.ConnectionId, out value);

        return Clients.All.notify(_connections.Count);
    }

    public override Task OnReconnected()
    {
        _connections.TryAdd(Context.ConnectionId, true);

        return Clients.All.notify(_connections.Count);
    }
}